<?php

namespace app\admin\model;

use think\Model;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Company extends Model
{
    public function getcompany($res)
    {
        $map = array();
        $admin = session('admin');
        //只显示所属自己的业务员的公司
        if ($admin['position_id'] == 63) {
            //采购员
            $map['a.saler_id'] = $admin['id'];
        } elseif ($admin['position_id'] == 60) {
            //采购经理
            $country_id = getValue('position', ['id' => $admin['position_id']], 'country_id');
            $pid = implode(',', array_column(getFrames('position', null, $country_id), 'id'));
            $adminmap['position_id'] = array('in', $pid);
            $saleids = implode(',', array_column(getables('admin', $adminmap, 'id'), 'id'));
            $map['a.saler_id'] = array('in', $saleids);
        }
        if ($res['status'] != '11') {
            //normal 正常   draft草稿 lock 锁定  del删除
            if (isset($res['status']) && $res['status']) {
                $map['a.status'] = $res['status'];
            }
        }
        //公司名、地址、邮编
        if (isset($res['dname']) && $res['dname']) {
            $maps['a.name'] = array('like', '%' . removeBlank($res['dname']) . '%');//公司名
            $maps['b.addr'] = array('like', '%' . removeBlank($res['dname']) . '%');//地址
            $maps['b.zipcode'] = array('like', '%' . removeBlank($res['dname']) . '%');//邮编
        } else {
            $maps = array();
        }
        //国家搜索
        if (isset($res['country_id']) && $res['country_id']) {
            $map['b.country_id'] = $res['country_id'];
        }
        //省份搜索
        if (isset($res['provinces_id']) && $res['provinces_id']) {
            $map['b.province_id'] = $res['provinces_id'];
        }
        //公司类型搜索
        if (isset($res['type_id']) && $res['type_id']) {
            $map['a.type_id'] = $res['type_id'];
        }
        $datares = $this->alias('a')->join('nt_co_profile b', 'a.id=b.co_id', 'left')->where(function ($query) use ($map) {
            $query->where($map);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->field('a.*,b.works,b.country_id,b.province_id,b.city_id,b.town_id,b.addr,b.zipcode')->order('a.create_at')->page($res['page'], $res['pageSize'])->select();
        //获取其他的数据
        $langs = $res['lang'];
        foreach ($datares as $datareskey => $dataresval) {
            //公司类型
            $cotypewhere['mkey'] = 'cotype_' . $dataresval['type_id'];
            $datares[$datareskey]['cotypename'] = getlangname('multi_lang', $cotypewhere, $langs);
            //业务员
            $datares[$datareskey]['salename'] = getinfo($dataresval['saler_id'], 'admin')['nickname'];
            $datares[$datareskey]['managename'] = getinfo($dataresval['update_id'], 'admin')['nickname'];
            $datares[$datareskey]['update_date'] = getTimeDate($dataresval['update_at'], 12);
            //时间
            if ($langs != 'zh') {
                $time = explode(' ', getTimeDate($dataresval['active_day'], 9));
                //活动时间
                $datares[$datareskey]['active_timeone'] = $time[0];
                $datares[$datareskey]['active_timetwo'] = $time[1];

            } else {
                $times = explode(' ', getTimeDate($dataresval['active_day']), 12);
                //活动时间
                $datares[$datareskey]['active_timeone'] = $times[0];
                $datares[$datareskey]['active_timetwo'] = $times[1];
            }
            //拼接用户的地址
            $datares[$datareskey]['address'] = $this->addresssget($dataresval['country_id'], $dataresval['province_id'], $dataresval['city_id'], $dataresval['town_id'], $langs);
            $datares[$datareskey]['works'] = $this->worksexdata($dataresval['works'], 1);//员工数量
        }

        $data['data'] = $datares;
        //当前页的ids
        $data['ids'] = array_column($datares, 'id');
        $data['count'] = $this->alias('a')->join('nt_co_profile b', 'a.id=b.co_id', 'left')->where(function ($query) use ($map) {
            $query->where($map);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->count();
        return $data;
    }

    //处理客户的删除与锁定的接口‘
    public function ulockadjustrecover($data)
    {
        //normal 正常   draft草稿 lock 锁定  del删除
        $ids = $data['id'];
        if ($ids) {
            //单独获取这个查询数据的状态
            $deldata = Db::name('company')->field('status,name')->where("id in($ids)")->select();
            $arrstatus = array_column($deldata, 'status');//状态
            $arrname = array_column($deldata, 'name');//公司名
            if (count($arrname) > 3) {
                $namecompany = $arrname[0] . $arrname[1] . $arrname[2] . '...';
            } else {
                $namecompany = implode(",", $arrname);
            }
        }
        if ($data['act'] == 'lock') {
            if (!$ids) {
                return array('msg' => lang("please_select_a_company_to_lock"), 'status' => 3);
            } else {
                $update['status'] = 'LOCK';//锁定
                $update['update_id'] = session('userid');//更新用户
                $update['update_at'] = time();//更新时间
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namecompany . lang("locked_successfully");
                $failed = $namecompany . lang("lock_failed");
            }
        } elseif ($data['act'] == 'del') {
            //伪删除
            if (!$ids) {
                return array('msg' => lang("please_select_a_company_to_delete"), 'status' => 3);
            } else {
                //锁定的公司不能删除
                if (in_array('LOCK', $arrstatus)) {
                    return array('msg' => $namecompany . lang("it's_locked_can't_be_deleted"), 'status' => 0);
                    exit;
                }
                $update['status'] = 'DEL';//删除
                $update['del_id'] = session('userid');//删除的用户
                $update['del_at'] = time();
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namecompany . lang("deleted_successfully");
                $failed = $namecompany . lang("failed_to_delete");
            }
        } elseif ($data['act'] == 'unlock') {
            if (!$ids) {
                return array('msg' => lang("please_select_a_company_to_unlock"), 'status' => 3);
            } else {
                $update['update_id'] = session('userid');//更新用户
                $update['update_at'] = time();//更新时间
                $update['status'] = 'NORMAL';//正常
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namecompany . lang("unlock_successful_");
                $failed = $namecompany . lang("unlock_failed");
            }
        } elseif ($data['act'] == 'recover') {
            if (!$ids) {
                return array('msg' => lang("please_select_a_company_to_restore"), 'status' => 3);
            } else {
                if (in_array('LOCK', $arrstatus)) {
                    return array('msg' => $namecompany . lang("status_locked_can't_be_recovered"), 'status' => 0);
                    exit;
                }
                $update['update_id'] = session('userid');//更新用户
                $update['update_at'] = time();//更新时间
                $update['status'] = 'NORMAL';//正常
                $update['del_id'] = 0;//删除者为0
                $update['del_at'] = 0;//删除时间
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namecompany . lang("recovery_successful");
                $failed = $namecompany . lang("recovery_failed");
            }
        } elseif ($data['act'] == 'clear') {
            if (!$ids) {
                return array('msg' => lang("please_select_a_company_to_clear"), 'status' => 3);
            } else {
                if (in_array('LOCK', $arrstatus)) {
                    return array('msg' => $namecompany . lang("it's_locked_can't_be_deleted"), 'status' => 0);
                    exit;
                }
                //数据的真正的删除
                $ret = $this->where("id in($ids)")->delete();
                $success = $namecompany . lang("cleared_successfully");
                $failed = $namecompany . lang("clear_failed");
            }
        }
        if ($ret === false) {
            return array('status' => 0, 'msg' => $failed);
        } else {
            return array('status' => 1, 'msg' => $success);
        }
    }

    //处理公司的添加和公司的接口
    public function addeditcompany($data)
    {
        $ckdata = notEmpty(['type_id' => lang("company_type"), 'name' => lang("company_name"), 'saler_id' => lang("employees")]);
        if ($ckdata['status'] == 2) {
            return $ckdata;
        }
        if (!$data['address']['country_id'] || !$data['address']['province_id'] || !$data['address']['city_id']) {
            return array('msg' => lang("address_can't_be_empty"), 'status' => 2);
        }
        $data['status'] = $data['statuss'];
        $data['active_day'] = time();//活动时间
        $data['trust'] = '1';//信任程度
        $data['country_id'] = $data['address']['country_id'];//国家id
        $data['province_id'] = $data['address']['province_id'];//省份id
        $data['city_id'] = $data['address']['city_id'];//城市id
        $data['town_id'] = $data['address']['town_id'];//城镇id
        if ($data['act'] == 'companyadd') {
            //公司已经添加过了就不用再添加
            $infocompany = $this->where('name', $data['name'])->find();
            if ($infocompany) {
                return array('msg' => $data['name'] . lang("already_exists"), 'status' => 3);
            }
            $data['update_id'] = $data['create_id'] = session('userid');
            $data['create_at'] = $data['update_at'] = time();
            Db::startTrans();
            $companyid = $this->strict(false)->insertGetId($data);//公司表
            $data['co_id'] = $companyid;//公司id
            $comprofileid = Db::name('co_profile')->strict(false)->insertGetId($data);//公司详情表
            //公司联系人写入
            if (isset($data['linkarr']) && $data['linkarr']) {
                $this->adddatacompany($data['linkarr'],$companyid, 1);
            }
            //处理公司账户的写入
            if (isset($data['bankarr']) && $data['bankarr']) {
                $this->adddatacompany($data['bankarr'], $companyid, 2);
            }
            //处理分公司的写入
            if (isset($data['brancharr']) && $data['brancharr']) {
                $this->adddatacompany($data['brancharr'], $companyid, 3);
            }
            //处理分公司的写入
            if (isset($data['evaluatearr']) && $data['evaluatearr']) {
                $this->adddatacompany($data['evaluatearr'], $companyid, 4);
            }
            //处理公司属性的写入
            if (isset($data['attrval']) && $data['attrval']) {
                $companycarid = $this->adddatacompany($data['attrval'],$companyid,5);
            }
            if ($companyid && $comprofileid) {
                Db::commit();
                return array('msg' => $data['name'] . lang("added_successfully"), 'status' => 1);
            } else {
                return array('msg' => $data['name'] . lang("add_failed"), 'status' => 0);
            }
        } elseif ($data['act'] == 'companyedit') {
            $info = $this->where('id', $data['co_id'])->find();
            if ($info['status'] == 'LOCK') {
                return array('msg' => $data['name'] . lang("status_locked_can't_be_edit"), 'status' => 0);
            }
            //判断公司类型是否改变
            if ($data['type_id'] != $info['type_id']) {
                Db::name('coattr_value')->where('co_id', $data['co_id'])->delete();
            }
            //编辑
            $updata = array(
                'type_id' => $data['type_id'],
                'name' => $data['name'],
                'status' => $data['statuss'],
                'saler_id' => $data['saler_id'],
                'update_id' => session('userid'),
                'update_at' => time(),
                'country_id' => $data['country_id'],
                'regno' => $data['regno'],
                'taxno' => $data['taxno'],
            );
            $upprodata = array(
                'remarks' => $data['remarks'],
                'works' => $data['works'],
                'country_id' => $data['country_id'],
                'province_id' => $data['province_id'],
                'city_id' => $data['city_id'],
                'town_id' => $data['town_id'],
                'addr' => $data['addr'],
                'zipcode' => $data['zipcode'],
                'update_id' => session('userid'),
                'update_at' => time(),
            );
            Db::startTrans();
            $companyupid = $this->where('id', $data['co_id'])->update($updata);//公司表
            $profileid = Db::name('co_profile')->where('co_id', $data['co_id'])->update($upprodata);//公司详情表

            //处理公司联系人的写入
            $linkmanarr = implode(',', array_column(Db::name('linkman')->where('co_id', $data['co_id'])->select(), 'id'));
            $maplink['linkman_id'] = array('in', $linkmanarr);
            Db::name('linkman_method')->where($maplink)->delete();//删除联系方式
            Db::name('linkman')->where('co_id', $data['co_id'])->delete();//删除联系人
            if (isset($data['linkarr']) && $data['linkarr']) {
                $this->adddatacompany($data['linkarr'], $data['co_id'], 1);
            }
            //处理公司账户的写入
            Db::name('co_bank')->where('co_id', $data['co_id'])->delete();//删除公司账户
            if (isset($data['bankarr']) && $data['bankarr']) {
                $this->adddatacompany($data['bankarr'], $data['co_id'], 2);
            }
            //处理分公司的写入
            Db::name('co_branch')->where('co_id', $data['co_id'])->delete();//删除分公司
            if (isset($data['brancharr']) && $data['brancharr']) {
                $this->adddatacompany($data['brancharr'], $data['co_id'], 3);
            }
            //处理分公司的写入
            Db::name('co_evaluate')->where('co_id', $data['co_id'])->delete();//删除风评
            if (isset($data['evaluatearr']) && $data['evaluatearr']) {
                $this->adddatacompany($data['evaluatearr'], $data['co_id'], 4);
            }
            //处理公司属性的写入
            if (isset($data['attrval']) && $data['attrval']) {
                $companycarid = $this->adddatacompany($data['attrval'],$data['co_id'],5);
            }
            //公司的编辑（联系人个银行无需更新）
            if ($companyupid !== false && $profileid !== false) {
                Db::commit();
                return array('msg' => $data['name'] . lang("edited_successfully"), 'status' => 1);
            } else {
                return array('msg' => $data['name'] . lang("edit_failed"), 'status' => 0);
            }
        }
    }

    //公司相关信息的写入
    public function adddatacompany($data, $co_id, $code)
    {
        if ($code == 1) {
            foreach ($data as $datakey => $dataval) {
                $dataval['co_id'] = $co_id;
                $dataval['create_id'] = $dataval['update_id'];
                $dataval['create_at'] = $dataval['update_at'];
                if($dataval['is_main']=='true'){
                    $dataval['is_main']='1';
                }elseif ($dataval['is_main']=='false'){
                    $dataval['is_main']='0';
                }
                if ($dataval['id']) {
                    //联系人的写入
                    $linkid = Db::name('linkman')->strict(false)->insertGetId($dataval);
                } else {
                    //联系人的写入
                    unset($dataval['id']);
                    $linkid = Db::name('linkman')->strict(false)->insertGetId($dataval);
                }
                foreach ($dataval['linkarr'] as $key => $val) {
                    $val['linkman_id'] = $linkid;
                    $val['content'] = trim($val['content']);
                    $val['create_id'] = $val['update_id'] = session('userid');
                    $val['create_at'] = $val['update_at'] = time();
                    if ($val['id']) {
                        //联系方式的写入
                        Db::name('linkman_method')->strict(false)->insertGetId($val);
                    } else {
                        //联系方式的写入
                        unset($val['id']);
                        Db::name('linkman_method')->strict(false)->insertGetId($val);
                    }
                }
            }
        } elseif ($code == 2) {
            //公司账户的写入
            foreach ($data as $datakey => $dataval) {
                $dataval['co_id'] = $co_id;
                $dataval['create_id'] = $dataval['update_id'];
                $dataval['create_at'] = $dataval['update_at'];
                if($dataval['is_main']=='true'){
                    $dataval['is_main']='1';
                }elseif ($dataval['is_main']=='false'){
                    $dataval['is_main']='0';
                }
                if ($dataval['id']) {
                    Db::name('co_bank')->strict(false)->insert($dataval);
                } else {
                    unset($dataval['id']);
                    Db::name('co_bank')->strict(false)->insert($dataval);
                }
            }
        }elseif ($code == 3) {
            //分公司的写入
            foreach ($data as $datakey => $dataval) {
                $dataval['co_id'] = $co_id;
                $dataval['create_id'] = $dataval['update_id'];
                $dataval['create_at'] = $dataval['update_at'];
                if($dataval['lock']=='true'){
                    $dataval['lock']='1';
                }elseif ($dataval['lock']=='false'){
                    $dataval['lock']='0';
                }
                if ($dataval['id']) {
                    Db::name('co_branch')->strict(false)->insert($dataval);
                } else {
                    unset($dataval['id']);
                    Db::name('co_branch')->strict(false)->insert($dataval);
                }
            }
        }elseif ($code == 4) {
            //风评的写入
            foreach ($data as $datakey => $dataval) {
                $dataval['co_id'] = $co_id;
                $dataval['create_id'] = $dataval['update_id'];
                $dataval['create_at'] = $dataval['update_at'];
                if ($dataval['id']) {
                    Db::name('co_evaluate')->strict(false)->insert($dataval);
                } else {
                    unset($dataval['id']);
                    Db::name('co_evaluate')->strict(false)->insert($dataval);
                }
            }
        }elseif ($code==5){
            Db::name('coattr_value')->where('co_id', $co_id)->delete();//删除公司属性
            if (isset($data['text']) && $data['text']) {
                foreach ($data['text'] as $key => $val) {
                    $textdata['co_id'] = $co_id;
                    $textdata['content'] = $val['val'];
                    $textdata['coattr_id'] = $val['key'];
                    Db::name('coattr_value')->insert($textdata);
                }
            }
            if (isset($data['select']) && $data['select']) {
                foreach ($data['select'] as $key => $val) {
                    if (isset($val['id']) && $val['id']) {
                        $selectdata['coattr_id'] = $val['id'];
                    } else {
                        $selectdata['coattr_id'] = $val['key'];
                    }
                    $selectdata['co_id'] = $co_id;
                    $selectdata['content'] = $val['val'];
                    Db::name('coattr_value')->insert($selectdata);
                }
            }
        }
    }

    //处理公司详情数据的接口
    public function getdetail($data)
    {
        $admin = session('admin');
        $lang = $data['lang'];//语言
        $id = '';
        if (isset($data['company_id'])) {
            $id = $data['company_id'];
        }
        if (isset($data['status']) && $data['status'] == 'detail') {
            //详情、详细资料
            $infodata = Db::name('company')->alias('a')->join('nt_co_profile b', 'a.id=b.co_id', 'left')->field('a.*,b.works,b.country_id,b.province_id,b.city_id,b.town_id,b.addr,b.zipcode,b.remarks')->where('a.id', $id)->find();
            //公司类型
            $wherecotype['mkey'] = 'cotype_' . $infodata['type_id'];
            $infodata['cotypename'] = getlangname('multi_lang', $wherecotype, $lang);
            //业务员
            $infodata['managename'] = getinfo($infodata['saler_id'], 'admin')['nickname'];
            //添加者
            $infodata['createname'] = getinfo($infodata['create_id'], 'admin')['nickname'];
            //编辑者
            $infodata['updatename'] = getinfo($infodata['update_id'], 'admin')['nickname'];
            //员工数量
            $infodata['worksnum'] = $this->worksexdata($infodata['works'], 1);
            //拼接用户地址
            $infodata['address'] = $this->addresssget($infodata['country_id'], $infodata['province_id'], $infodata['city_id'], $infodata['town_id'], $lang);
            //编辑时间
            $infodata['update_date'] = getTimeDate($infodata['update_at'], 12);
            if ($lang != 'zh') {
                //添加时间
                $infodata['create_date'] = getTimeDate($infodata['create_at'], 9);
            } else {
                //添加时间
                $infodata['create_date'] = getTimeDate($infodata['create_at'], 12);
            }
            //获取对应的公司的属性名称
            $selectdata = $textdata = array();
            //获取公司的属性
            $attrdata = array_unique(array_column(Db::name('coattr_value')->where('co_id', $id)->select(), 'coattr_id'));//属性id（去重）
            foreach ($attrdata as $attrdatakey => $attrdataval) {
                //判断属性是select还是文本框
                $coattrinfo = Db::name('coattr')->field('id,is_text,mkey')->where('id', $attrdataval)->find();
                if ($coattrinfo['is_text'] == 1) {
                    //select框
                    $wherecoattr['mkey'] = 'coattr_' . $coattrinfo['id'];
                    //选择框,获取对应的属性名称
                    $getlangname = getlangname('multi_lang', $wherecoattr, $lang);
                    $selecid=getValue('coattr_value',['co_id'=>$id,'coattr_id'=>$coattrinfo['id']],'content');
                    $contname=getValue('coattr_select',['id'=>$selecid],'option_text');
                    $selectdata[]=array('key'=>$getlangname,'val'=>$contname);
                } else {
                    //文本框
                    $wherecoattr['mkey'] = 'coattr_' . $coattrinfo['id'];
                    $getlangname = getlangname('multi_lang', $wherecoattr, $lang);
                    //属性值
                    $getname=getValue('coattr_value',['co_id'=>$id,'coattr_id'=>$coattrinfo['id']],'content');
                    $textdata[]=array('key'=>$getlangname,'val'=>$getname);
                }
            }
            $infodata['textdata'] = $textdata;//文本框
            $infodata['selectdata'] = $selectdata;//select框
            $resdata = array('data' => $infodata);
        } elseif (isset($data['status']) && $data['status'] == 'information') {
            //销售资料
            $month = getTimeDate(null, 2);
            $co_saledata = Db::name('co_sale')->where(['co_id' => $id, 'branch_id' => 0])->find();
            if ($co_saledata) {
                //支付类型和送货方式
                $mappayids['id'] = array('in', $co_saledata['pay_type_ids']);
                $code = array_column(getables('sale_pay_type', $mappayids, 'code'), 'code');
                $co_saledata['payname'] = implode("/", $code);
                $co_saledata['delivertype'] = getValue('sale_delivery_type', ['id' => $co_saledata['delivery_id']], 'code');
                //获取当月上月的数据
                $year = getTimeDate(null, 1);
                $month = getTimeDate(null, 2);
                $mapone['sale_year'] = $year;
                $mapone['sale_month'] = $month;
                $maptwo['co_id'] = $mapone['co_id'] = $id;
                $maptwo['branch_id'] = $mapone['branch_id'] = 0;
                $co_monthone = Db::name('co_sale_month')->where($mapone)->find();//当月数据
                if ($co_monthone) {
                    $co_saledata['sale_qtyone'] = $co_monthone['sale_qty'];//当月订单数
                    $co_saledata['paid_totalone'] = $co_monthone['paid_total'];//销售额
                    $co_saledata['troubleone'] = $co_monthone['trouble'];//故障数
                    $co_saledata['trouble_valueone'] = $co_monthone['trouble_value'];//故障金额
                    $co_saledata['mongrow'] = $co_monthone['grow'];//月成长
                }
                if ($month == '01') {
                    $maptwo['sale_year'] = $year - 1;
                    $maptwo['sale_month'] = 12;
                } else {
                    $maptwo['sale_year'] = $year;
                    $maptwo['sale_month'] = $month - 1;
                }
                $co_lastmonth = Db::name('co_sale_month')->where($maptwo)->find();//上月数据
                if ($co_lastmonth) {
                    $co_saledata['sale_qtytwo'] = $co_lastmonth['sale_qty'];//上月订单数
                    $co_saledata['paid_totaltwo'] = $co_lastmonth['paid_total'];//上月销售额
                    $co_saledata['troubletwo'] = $co_lastmonth['trouble'];//上月故障数
                    $co_saledata['trouble_valuetwo'] = $co_lastmonth['trouble_value'];//上月故障金额
                }
                //年成长
                $mongrows['co_id'] = $data['company_id'];
                $mongrows['branch_id'] = 0;
                $mongrows['sale_year'] = $year;
                $mongrows['sale_month'] = 0;
                $co_saledata['mongrows'] = getValue('co_sale_month', $mongrows, 'grow');
            }else{
                $co_saledata=array();
            }
            $resdata = array('data' => $co_saledata);
        } elseif (isset($data['status']) && $data['status'] == 'link') {
            //联系人
            $maplink['co_id'] = $id;//公司id
            //获取公司的联系人
            $list = Db::name('linkman')->where($maplink)->field('id,name,is_main,sex,position,update_at,update_id')->select();
            foreach ($list as $key => $value) {
                //性别
                $list[$key]['sexman'] = $this->worksexdata($value['sex'], 2);
                //编辑时间
                $list[$key]['update_date'] = getTimeDate($value['update_at'], 12);
                //编辑者
                $list[$key]['updatename'] = getValue('admin', ['id' => $value['update_id']], 'nickname');
                //通过联系人的id，获取该联系人的方式
                $linkcon = Db::name('linkman_method')->where('linkman_id', $value['id'])->field('id,coattr_id,content')->select();
                //获取联系方式的名称
                foreach ($linkcon as $linkey => $linvalue) {
                    //获取这个用户的联系方式名称
                    $coattrwhere['mkey'] = 'coattr_' . $linvalue['coattr_id'];
                    $one = getlangname('multi_lang', $coattrwhere, $lang);//联系方式
                    $linkcon[$linkey]['linkname'] = $one;
                }
                //联系，名称
                $list[$key]['linkarr'] = $linkcon;
            }
            $resdata['data'] = $list;
            $resdata['size'] = Db::name('linkman')->where($maplink)->count();
            //获取的是国家的联系方式
            $resdata['linkfun'] = $this->getmethname($data['country_id'], $lang, 1);
        } elseif (isset($data['status']) && $data['status'] == 'bank') {
            //银行
            $mapbank['a.co_id'] = $id;//公司id
            //获取所有的联系人
            $join = [
                ['nt_banks b', 'a.banks_id=b.id']
            ];
            $list = Db::name('co_bank')->alias('a')->join($join)->field('a.id,a.banks_id,b.name,a.bankname,a.account_name,a.account_num,a.is_main,a.update_at,a.update_id')->where($mapbank)->select();
            foreach ($list as $key => $value) {
                //编辑时间
                $list[$key]['update_date'] = getTimeDate($value['update_at'], 12);
                //编辑者
                $list[$key]['updatename'] = getValue('admin', ['id' => $value['update_id']], 'nickname');
            }
            $resdata['data'] = $list;
            $resdata['size'] = Db::name('co_bank')->alias('a')->join($join)->where($mapbank)->count();
            $resdata['bankdata'] = $this->getmethname($data['country_id'], $lang, 2);
        } elseif (isset($data['status']) && $data['status'] == 'branch') {
            //分公司
            $mapbranch['co_id'] = $id;//公司id
            //获取所有的子公司
            $list = Db::name('co_branch')->where($mapbranch)->field('id,name,lock,country_id,province_id,city_id,town_id,addr,works,regno,taxno,update_at,update_id,zipcode')->select();
            foreach ($list as $key => $value) {
                //编辑时间
                $list[$key]['update_date'] = getTimeDate($value['update_at'], 12);
                //编辑者
                $list[$key]['updatename'] = getValue('admin', ['id' => $value['update_id']], 'nickname');
                //地址
                $list[$key]['address'] = $this->addresssget($value['country_id'], $value['province_id'], $value['city_id'], $value['town_id'], $lang);
                //员工数量
                $list[$key]['worksnum'] = $this->worksexdata($value['works'], 1);
            }
            $databranch = $this->cotymancoun($lang, $admin['position_id']);
            $resdata['data'] = $list;
            $resdata['number'] = $databranch['works'];//员工数量
            $resdata['countryname'] = $databranch['countryname'];//国家
            $resdata['lang'] = $lang;//语言
            $resdata['ids'] = array_column($list, 'id');
            $resdata['size'] = Db::name('co_branch')->where($mapbranch)->count();
        } elseif (isset($data['status']) && $data['status'] == 'evaluate') {
            //公司风评
            $mapevaluate['co_id'] = $id;//公司id
            //获取该公司的风评
            $list = Db::name('co_evaluate')->where($mapevaluate)->field('id,comment,score,update_id,update_at')->select();
            foreach ($list as $key => $value) {
                //编辑时间
                $list[$key]['update_date'] = getTimeDate($value['update_at'], 12);
                //编辑者
                $list[$key]['updatename'] = getValue('admin', ['id' => $value['update_id']], 'nickname');
            }
            $resdata['data'] = $list;
            $resdata['size'] = Db::name('co_evaluate')->where($mapevaluate)->count();
        } elseif (isset($data['status']) && $data['status'] == 'sale') {
            //销售订单下的产品
            $mapsale['co_id'] = $id;
            //只显示自己的产品
//            if($admin['position_id']==63){
//                //采购员
//                $mapsale['saler_id'] = $admin['id'];
//            }elseif ($admin['position_id']==60){
//                //采购经理
//                $country_id=getValue('position',['id'=>$admin['position_id']],'country_id');
//                $pid = implode(',',array_column(getFrames('position', null, $country_id), 'id'));
//                $adminmap['position_id']=array('in',$pid);
//                $saleids=implode(',',array_column(getables('admin',$adminmap,'id'),'id'));
//                $mapsale['saler_id'] = array('in',$saleids);
//            }
            $saledata = getables('sale', $mapsale, 'id');
            $sale_ids = implode(",", array_column($saledata, 'id'));//销售id
            $mapsale_id['sale_id'] = array('in', $sale_ids);
            //该公司的所有产品
            $prodata = Db::name('sale_detail')->field('id,sale_id,pro_id,prochar_id')->where($mapsale_id)->group('prochar_id')->select();

            //销售订单
            $saleids = Db::name('sale')->field('id,create_at')->where('co_id', $data['company_id'])->page($data['page'], $data['pageSize'])->select();

            $resdata['size'] = Db::name('sale')->where('co_id', $data['company_id'])->count();

            foreach ($saleids as $saleidskey => $saleidsval) {
                $saleids[$saleidskey]['create_date'] = getTimeDate($saleidsval['create_at'], 15);
                foreach ($prodata as $prodatakey => $prodataval) {
                    //产品信息
                    $prodata[$prodatakey]['prodata'] = getProAndProchar($prodataval, $data['lang'], 48);
                    $mappro['sale_id'] = $saleidsval['id'];
                    $mappro['pro_id'] = $prodataval['pro_id'];
                    $mappro['prochar_id'] = $prodataval['prochar_id'];
                    //一个销售订单不会出现多个同样的产品
                    $infopro = Db::name('sale_detail')->where($mappro)->find();//订单数量
                    $prodata[$prodatakey]['prosum'][] = array(
                        'qty' => $infopro['qty'],//订单数量
                        'price' => $infopro['price'],//订单单价
                        'sumprice' => $infopro['qty'] * $infopro['price']
                    );
                }
            }
            //每一个销售订单的合计
            foreach ($prodata as $prodatakeys => $prodatavals) {
                $sumqty = array_sum(array_column($prodatavals['prosum'], 'qty'));//总数量
                $sumprice = array_sum(array_column($prodatavals['prosum'], 'sumprice'));//总价格
                if ($sumqty == 0) {
                    $prodata[$prodatakeys]['sumprice'] = '';
                    $prodata[$prodatakeys]['sumqty'] = '';
                } else {
                    $prodata[$prodatakeys]['sumprice'] = $sumprice / $sumqty;
                    $prodata[$prodatakeys]['sumqty'] = $sumqty;
                }

            }
            $resdata['data'] = $saleids;
            $resdata['prodata'] = $prodata;
        } elseif (isset($data['status']) && $data['status'] == 'buypo') {
            //销售订单下的合同
            $mapsale['co_id'] = $id;
            $list = Db::name('sale')->where($mapsale)->page($data['page'], $data['pageSize'])->select();
            foreach ($list as $listkey => $listval) {
                $list[$listkey]['finish_date'] = getTimeDate($listval['finish_at'], 15);
                $list[$listkey]['saler_name'] = getValue('admin', ['id' => $listval['saler_id']], 'nickname');
                $list[$listkey]['create_name'] = getValue('admin', ['id' => $listval['create_id']], 'nickname');
                $list[$listkey]['create_date'] = getTimeDate($listval['create_at'], 15);
                $list[$listkey]['update_name'] = getValue('admin', ['id' => $listval['update_id']], 'nickname');
                $list[$listkey]['update_date'] = getTimeDate($listval['update_at'], 15);
            }
            $count = Db::name('sale')->where($mapsale)->count();
            $resdata['data'] = $list;
            $resdata['size'] = $count;
        } elseif (isset($data['status']) && $data['status'] == 'buyplan') {
            //采购订单下的产品
            $mapbuyplan['company_id'] = $id;
            if ($admin['position_id'] == 63) {
                //采购员
                $mapbuyplan['create_id'] = $admin['id'];
                $mapsum['create_id'] = $admin['id'];
            } elseif ($admin['position_id'] == 60) {
                //采购经理
                $country_id = getValue('position', ['id' => $admin['position_id']], 'country_id');
                $pid = implode(',', array_column(getFrames('position', null, $country_id), 'id'));
                $adminmap['position_id'] = array('in', $pid);
                $buyids = implode(',', array_column(getables('admin', $adminmap, 'id'), 'id'));
                $mapbuyplan['create_id'] = array('in', $buyids);
                $mapsum['create_id'] = array('in', $buyids);
            }
            $list = Db::name('buy_plan')->where($mapbuyplan)->field('id,pro_id,prochar_id,company_id')->page($data['page'], $data['pageSize'])->group('prochar_id')->select();
            foreach ($list as $listkey => $listval) {
                //产品信息
                $list[$listkey]['prodata'] = getProAndProchar($listval, $data['lang'], 48);
                //订单量
                $mapsum['pro_id'] = $listval['pro_id'];
                $mapsum['prochar_id'] = $listval['prochar_id'];
                $mapsum['company_id'] = $listval['company_id'];
                //同一个公司可能有多个采购订单有相同的产品
                $list[$listkey]['pronum'] = Db::name('buy_plan')->where($mapsum)->sum('qty');
                //最后下单时间
                $final = Db::name('buy_plan')->where($mapsum)->order('create_at desc')->select();
                $list[$listkey]['create_date'] = getTimeDate($final[0]['create_at'], 15);
                //最后下单价格
                $list[$listkey]['price'] = $final[0]['price'];
            }
            $count = Db::name('buy_plan')->where($mapbuyplan)->count();
            $resdata['data'] = $list;
            $resdata['size'] = $count;
        } elseif (isset($data['status']) && $data['status'] == 'buylist') {
            //采购订单下的合同
            $mapbuypo['company_id'] = $id;//公司id;
            if ($admin['position_id'] == 63) {
                //采购员
                $mapbuypo['create_id'] = $admin['id'];
            } elseif ($admin['position_id'] == 60) {
                //采购经理
                $country_id = getValue('position', ['id' => $admin['position_id']], 'country_id');
                $pid = implode(',', array_column(getFrames('position', null, $country_id), 'id'));
                $adminmap['position_id'] = array('in', $pid);
                $buyids = implode(',', array_column(getables('admin', $adminmap, 'id'), 'id'));
                $mapbuypo['create_id'] = array('in', $buyids);
            }
            $list = Db::name('buy_po')->where($mapbuypo)->page($data['page'], $data['pageSize'])->select();
            foreach ($list as $listkey => $listval) {
                $list[$listkey]['delivery_date'] = getTimeDate($listval['delivery_day'], 15);
                $list[$listkey]['port_name'] = getValue('port', ['id' => $listval['port_id']], 'name');
                $list[$listkey]['update_date'] = getTimeDate($listval['update_at'], 12);
                //编辑者
                $list[$listkey]['updatename'] = getValue('admin', ['id' => $listval['update_id']], 'nickname');
            }
            $count = Db::name('buy_po')->where($mapbuypo)->count();
            $resdata['data'] = $list;
            $resdata['size'] = $count;
        } elseif (isset($data['status']) && $data['status'] == 'companyedit') {
            //公司编辑
            $resdata = $this->cotymancoun($lang, $admin['position_id']);
            //接口
            $info = Db::name('company')->alias('a')->join('nt_co_profile b', 'a.id=b.co_id', 'left')->field('a.*,b.works,b.country_id,b.province_id,b.city_id,b.town_id,b.addr,b.zipcode,b.remarks')->where('a.id', $id)->find();
            //获取公司的的属性值
            $info['coattrdata'] = Db::name('coattr_value')->where('co_id', $id)->select();
            $coattrss['cotype'] = $info['type_id'];
            $coattrss['lang'] = $lang;
            $coattrss['country_id'] = $info['country_id'];
            $textselctname = $this->indocoattrss($coattrss);
            $info['typeselect'] = $textselctname;
            //编辑返回的数据
            $resdata['lang'] = $lang;
            $resdata['info'] = $info;
        } elseif (isset($data['status']) && $data['status'] == 'companyadd') {
            //公司添加
            $resdata = $this->cotymancoun($lang, $admin['position_id']);
            $resdata['lang'] = $lang;
        }
        return $resdata;
    }

    //获取国家的联系方式名称和银行
    public function getmethname($country_id = '', $lang, $code)
    {
        $mapbank = array();
        if ($country_id) {
            //使用自己国家的联系方式和通用国家的联系方式
            $mapcoattr['a.country_id'] = array('in', [0, $country_id]);;
            $mapbank['country_id'] = $country_id;
        }
        $mapcoattr['a.is_text'] = 0;//文本
        $mapcoattr['a.person'] = 1;//使用与个人
        $mapcoattr['a.del_id'] = 0;//未删除
        //获取联系名称
        if ($code == 1) {
            //返回联系名称
            $data = getlangres('coattr', $lang, 'a.id,b.content', $mapcoattr);
        } else {
            //返回国家银行
            $data = Db::name('banks')->field('id,name')->where($mapbank)->select();
        }
        return $data;
    }

    //处理公司类型业务员和国家
    protected function cotymancoun($lang, $id)
    {
        //获取登录用户所属的国家
        $country_id = getValue('position', ['id' => $id], 'country_id');
        $where['a.lang'] = $lang;//语言标志
        //公司类型是授权给不同的职位的
        if ($id != 1) {
            $where[] = ["exp", "FIND_IN_SET($id,position_ids)"];
        }
        $join = [
            ['nt_cotype b', 'a.mkey=b.mkey']
        ];
        $table = 'multi_lang';
        //公司类型
        $cotypename = getmultidata($table, $join, $where)['data'];
        //国家
        $mapcountry = array();
        if ($id != 1 && $id != 2) {
            $mapcountry['id'] = $country_id;
        }
        $countryname = getables('country', $mapcountry, 'id,name');
        $works = array('1' => '1-10', '2' => '11-20', '3' => '21-50', '4' => '51-100', '5' => '100+');
        return array('cotypename' => $cotypename, 'countryname' => $countryname, 'works' => $works);
    }

    //拼接用户的地址
    public function addresssget($country_id, $province_id, $city_id, $town_id, $lang)
    {
        //拼接用户地址
        $country = getinfo($country_id, 'country')['name'];//国家
        $provinces = getinfo($province_id, 'provinces')['name'];//省
        $city = getinfo($city_id, 'city')['name'];//城市
        $town = getinfo($town_id, 'town')['name'];//镇
        if ($provinces == $city) {
            $prci = ' ' . $provinces . ' ';
        } else {
            if ($lang != 'zh') {
                $prci = ' ' . $city . ' ' . $provinces . ' ';
            } else {
                $prci = ' ' . $provinces . ' ' . $city . ' ';
            }
        }
        if ($lang != 'zh') {
            $address = $town . $prci . $country;
        } else {
            $address = $country . $prci . $town;
        }
        return $address;
    }

    //处理员工的数量的显示
    public function worksexdata($ststus, $code)
    {
        switch ($ststus) {
            case '0':
                $sex = lang("woman");
                break;
            case '1':
                $works = '1-10';
                $sex = lang("man");
                break;
            case '2':
                $works = '11-20';
                break;
            case '3':
                $works = '21-50';
                break;
            case '4':
                $works = '51-100';
                break;
            case '5':
                $works = '100+';
                break;
        }
        if ($code == 1) {
            return $works;
        } elseif ($code == 2) {
            return $sex;
        }
    }

    public function indocoattrss($res)
    {
        $cotype = $res['cotype'];//分类名称
        $rescoa = array();
        //匹配公司类型属性
        $where['b.cotype_ids'] = array('like', '%' . $cotype . '%');
        $where['b.person'] = 0;//使用公司的属性
        //获取分类名称
        $where['a.lang'] = $res['lang'];//语言标志
        $where['b.country_id'] = array('in', ['0', $res['country_id']]);
        $join = [
            ['nt_coattr b', 'a.mkey=b.mkey']
        ];
        $table = 'multi_lang';
        $coarr = getmultidata($table, $join, $where)['data'];//属性信息
        //获取对应的属性中值，select,text
        foreach ($coarr as $cokey => $covalue) {
            if ($covalue['is_text'] == 1) {
                //select框
                $res = Db::name('coattr_select')->where('coattr_id', $covalue['id'])->select();
                foreach ($res as $reskey => $resvalue) {
                    $coarr[$cokey]['textselect'][] = array('content' => $resvalue['option_text'], 'id' => $resvalue['id']);
                }
            } else if ($covalue['is_text'] == 0) {
                //文本框
                $coarr[$cokey]['textselect'][] = array();
            }
        }
        //对获取的select进行处理
        return $coarr;
    }

    //员工的批量调整接口显示
    public function getcompanydatas($data)
    {
        $ids = $data['ids'];
        $langs = $data['lang'];
        //国家，公司类型,员工数量，业务员
        $admin = session('admin');
        $resdata = $this->cotymancoun($langs, $admin['position_id']);
        //查询要批量编辑的的数据
        $datares = Db::name('company')->alias('a')->join('nt_co_profile b', 'a.id=b.co_id', 'left')->where("a.id in($ids)")->field('a.*,b.works,b.country_id,b.province_id,b.city_id,b.town_id,b.addr')->page($data['page'], $data['pageSize'])->order('a.type_id desc,a.name desc')->select();
        foreach ($datares as $datareskey => $dataresval) {
            //公司类型
            $cotypewhere['mkey'] = 'cotype_' . $dataresval['type_id'];
            $datares[$datareskey]['cotypename'] = getlangname('multi_lang', $cotypewhere, $langs);
            //业务员
            $datares[$datareskey]['managename'] = getinfo($dataresval['saler_id'], 'admin')['nickname'];
            //拼接用户的地址
            $country = getinfo($dataresval['country_id'], 'country')['name'];//国家
            $provinces = getinfo($dataresval['province_id'], 'provinces')['name'];//省
            $city = getinfo($dataresval['city_id'], 'city')['name'];//城市
            $town = getinfo($dataresval['town_id'], 'town')['name'];//镇
            //地址
            $datares[$datareskey]['address'] = $country . ' ' . $provinces . ' ' . $city . ' ' . $town;
            $datares[$datareskey]['works'] = $this->worksexdata($dataresval['works'], 1);//员工数量
        }
        $resdata['data'] = $datares;
        //当前页的ids
        $resdata['ids'] = array_column($datares, 'id');
        $resdata['count'] = Db::name('company')->alias('a')->join('nt_co_profile b', 'a.id=b.co_id', 'left')->where("a.id in($ids)")->count();
        $resdata['lang'] = $langs;
        return $resdata;
    }

    //公司的批量调整
    public function batchall($data)
    {
        $ids = $data['ids'];
        $comid = '';
        if (!$ids) {
            return array('msg' => lang("please_select_a_company_to_batch_adjustment"), 'status' => 0);
            exit;
        } else {
            $ddata = Db::name('company')->field('name')->where("id in($ids)")->select();
            $arrname = array_column($ddata, 'name');//公司名
            if (count($arrname) > 3) {
                $namecompany = $arrname[0] . $arrname[1] . $arrname[2] . '...';
            } else {
                $namecompany = implode(",", $arrname);
            }
        }
        //编辑地址时，所有的地址都要填写
        if (isset($data['country_id']) && $data['country_id']) {
            //国家填写了
            if (!isset($data['town_id']) || !$data['town_id']) {
                return array('msg' => '地址请选择完整', 'status' => 0);
                exit;
            } else {
                //其他地址都填写了
                Db::name('co_profile')->where('co_id', 'in', $data['ids'])->setField('country_id', $data['country_id']);
                $this->where('id', 'in', $data['ids'])->setField('country_id', $data['country_id']);
                //省份
                Db::name('co_profile')->where('co_id', 'in', $data['ids'])->setField('province_id', $data['province_id']);
                Db::name('co_profile')->where('co_id', 'in', $data['ids'])->setField('city_id', $data['city_id']);
                Db::name('co_profile')->where('co_id', 'in', $data['ids'])->setField('town_id', $data['town_id']);
                $comid = 1;
            }
        }
        //员工数量
        if (isset($data['works']) && $data['works']) {
            Db::name('co_profile')->where('co_id', 'in', $data['ids'])->setField('works', $data['works']);
            $comid = 1;
        }
        //指定业务员
        if (isset($data['saler_id']) && $data['saler_id']) {
            //指定业务员
            $this->where('id', 'in', $data['ids'])->setField('saler_id', $data['saler_id']);
            $comid = 1;
        }
        //指定公司类型
        if (isset($data['cotype_id']) && $data['cotype_id']) {
            $cotypedata = $this->where('id', 'in', $data['ids'])->field('type_id,id')->select();
            //指定公司类型
            foreach ($cotypedata as $keys => $values) {
                if ($values['type_id'] != $data['cotype_id']) {
                    $this->where('id', $values['id'])->setField('type_id', $data['cotype_id']);
                    //改变的类型与原来的不一样,删除对应的这个公司的属性
                    Db::name('coattr_value')->where('co_id', $values['id'])->delete();
                }
            }
            $comid = 1;
        }
        if (!$comid) {
            return array('msg' => lang("please_select_the_type_to_edit"), 'status' => 0);
        } else {
            return array('msg' => $namecompany . lang("batch_adjustment_successful"), 'status' => 1);
        }
    }

    //获取公司的名称
    public function getcompanyname($data)
    {

        $map['status'] = 'NORMAL';
        if ($data['dname']) {
            $map['name'] = ['like', '%' . $data['dname'] . '%'];
        }
        if (isset($data['type_id'])) {
            $map['type_id'] = $data['type_id'];
        }
        if (isset($data['saler_id'])) {
            $map['saler_id'] = $data['saler_id'];
        }
        $datares = Db::name('company')->field('id,name')->where($map)->select();
        return $datares;
    }
}


